<?php

namespace App\Admin\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\AdminRoleUser;
use App\Models\Article;
use App\Models\BrandSort;
use App\Models\Course;
use App\Models\Doctor;
use App\Models\DoctorWorks;
use App\Models\Order;
use App\Models\ProductGoods;
use App\Models\ProductSort;
use App\Models\VisitUser;
use App\Models\WorkRelateGoods;
use App\Models\WorkRoomSortCategory;
use App\Util\Tool;
use App\Util\Url;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Auth\Database\Administrator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\MessageBag;
use Illuminate\Http\Request;

/**
 * 此项目由百凯伦公司研发，后面省略一万字
 */
class WorkListController extends Controller
{


    public function index(Request $request)
    {
        $userid = auth()->user()->id ?? 0;
        $types = auth()->user()->types;
        $hospital_id = auth()->user()->hospital_id;
        //判断用户是否是医院账号
        $role_list = AdminRoleUser::where(['user_id'=>$userid])->pluck("role_id")->toArray();
        if (!$userid || $types !=4 || $hospital_id ==0 || !in_array(11,$role_list)) {
            return redirect("admin/auth/logout");
        }
        $keyworld = $request->query("keyworld")??"";
        $w = [];
        if(!empty($keyworld)){
            $w[] = ['m.work_name','like','%'.$keyworld.'%'];
        }
        $start_time = request()->get("start_time");
        $end_time = request()->get("end_time");
        if(!empty($start_time) && !empty($end_time)){
            $w[] = [function ($query) use ($start_time,$end_time) {
                $query->whereBetween('o.created_at', [$start_time, $end_time]);
            }];
        }
        $page = $request->query("page");
        $work_ids = (new DoctorWorks())->where(['status'=>1,'hospital_id'=>$hospital_id])->pluck("id")->toArray();
        $data = DB::table('c_doctor_works as m')
            ->select('m.work_name', 'm.id', 'm.clinic_id','d.real_name', 'c.classify_name', DB::raw('count(o.id) as order_count'))
            ->leftJoin('c_address_books as o', 'm.id', '=', 'o.work_id')
            ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')
            ->leftJoin('c_doctors as d', 'm.id', '=', 'd.work_id')
            ->whereIn("m.id", $work_ids)
            ->where("d.is_admin",'=',1)
            ->where($w)
            ->groupBy('m.id')
            ->orderBy('order_count', 'desc')
            ->paginate(10);
        return view('admin.worklist', compact('data','keyworld','start_time','end_time'));
    }


    /***
     * @param Request $request
     * @return
     * 工作室咨询列表
     */
    public function getWorkConsultList(Request $request)
    {
        $userid = auth()->user()->id ?? 0;
        $types = auth()->user()->types;
        $hospital_id = auth()->user()->hospital_id;
        //判断用户是否是医院账号
        $role_list = AdminRoleUser::where(['user_id'=>$userid])->pluck("role_id")->toArray();
        if (!$userid || $types !=4 || $hospital_id ==0 || !in_array(11,$role_list)) {
            return redirect("admin/auth/logout");
        }
        $w_id = $request->query("w_id")??"";
        $start_time = request()->get("start_time");
        $end_time = request()->get("end_time");
        $w = [];
        if(!empty($w_id)){
            $w[] = ['c_doctor_works.id','=',$w_id];
        }
        $work_ids = (new DoctorWorks())->where(['status'=>1,'hospital_id'=>$hospital_id])->pluck("id")->toArray();
        $work_list = (new DoctorWorks())->select("id","work_name")->where(['status'=>1,'hospital_id'=>$hospital_id])->get()->toArray();
        $data = (new DoctorWorks())->withCount('order')
//                ->select('c_doctor_works.work_name', 'c_doctor_works.id', 'c_doctor_works.clinic_id','d.real_name', 'c.classify_name')
//                ->join("c_orders as order",'order.id','=','order_goods.order_id')
                ->addSelect('d.real_name','c.classify_name')
                ->leftJoin('c_clinic_categories as c', 'c_doctor_works.clinic_id', '=', 'c.id')
                ->leftJoin('c_doctors as d', 'c_doctor_works.id', '=', 'd.work_id')
                ->whereIn("c_doctor_works.id", $work_ids)
//                ->whereIn("o.order_type", [3,4])
//                ->where("o.pay_status",'=',1)
                ->where("d.is_admin",'=',1)
                ->where($w)
                ->groupBy('c_doctor_works.id')
                ->orderBy('order_count', 'desc')
                ->paginate(10);
//            dd($data);
//        $data = DB::table('c_doctor_works as m')
//            ->select('m.work_name', 'm.id', 'm.clinic_id','d.real_name', 'c.classify_name', DB::raw('count(o.id) as order_count'))
//            ->leftJoin('c_orders as o', 'm.id', '=', 'o.work_id')
//            ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')
//            ->leftJoin('c_doctors as d', 'm.id', '=', 'd.work_id')
//            ->whereIn("m.id", $work_ids)
//            ->whereIn("o.order_type", [3,4])
//            ->where("o.pay_status",'=',1)
//            ->where("o.order_status",'<=',2)
//            ->where("d.is_admin",'=',1)
//            ->where($w)
//            ->groupBy('m.id')
//            ->orderBy('order_count', 'desc')
//            ->paginate(10);
        return view('admin.workconsultlist', compact('data','w_id','work_list','start_time','end_time'));
    }



    /***
     * @param Request $request
     * @return
     * 工作室随访统计
     */
    public function getWorkFollowList(Request $request)
    {
        $userid = auth()->user()->id ?? 0;
        $types = auth()->user()->types;
        $hospital_id = auth()->user()->hospital_id;
        //判断用户是否是医院账号
        $role_list = AdminRoleUser::where(['user_id'=>$userid])->pluck("role_id")->toArray();
        if (!$userid || $types !=4 || $hospital_id ==0 || !in_array(11,$role_list)) {
            return redirect("admin/auth/logout");
        }
        $keyworld = $request->query("keyworld")??"";
        $w = [];
        if(!empty($keyworld)){
            $w[] = ['m.work_name','like','%'.$keyworld.'%'];
        }
        $work_ids = (new DoctorWorks())->where(['status'=>1,'hospital_id'=>$hospital_id])->pluck("id")->toArray();
        $data = DB::table('c_doctor_works as m')
            ->select('m.work_name', 'm.id', 'm.clinic_id','d.real_name', 'c.classify_name')
//            ->leftJoin('c_orders as o', 'm.id', '=', 'o.work_id')
            ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')
            ->leftJoin('c_doctors as d', 'm.id', '=', 'd.work_id')
            ->whereIn("m.id", $work_ids)
            ->where("d.is_admin",'=',1)
            ->where($w)
            ->groupBy('m.id')
            ->orderBy('m.id', 'desc')
            ->paginate(10);
        $dayStart = Carbon::now()->startOfDay();
        $dayEnd = Carbon::now()->endOfDay();
        //已随访的工作室数
        foreach ($data->items() as &$v) {
            $v->follow = '否';
            $isfollow_num = (new VisitUser())->whereBetween('created_at', [$dayStart, $dayEnd])->where("work_id", $v->id)->first();
            if($isfollow_num){
                $v->follow = '是';
            }
        }
        return view('admin.workfollowlist', compact('data','keyworld'));
    }


    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     * 工作室参与咨询数
     */
    public function getWorkAddConsultList(Request $request)
    {
        $userid = auth()->user()->id ?? 0;
        $types = auth()->user()->types;
        $hospital_id = auth()->user()->hospital_id;
        //判断用户是否是医院账号
        $role_list = AdminRoleUser::where(['user_id'=>$userid])->pluck("role_id")->toArray();
        if (!$userid || $types !=4 || $hospital_id ==0 || !in_array(11,$role_list)) {
            return redirect("admin/auth/logout");
        }
        $w_id = $request->query("w_id")??"";
        $w = [];
        if(!empty($w_id)){
            $w[] = ['m.id','=',$w_id];
        }
        $work_ids = (new DoctorWorks())->where(['status'=>1,'hospital_id'=>$hospital_id])->pluck("id")->toArray();
        $work_list = (new DoctorWorks())->select("id","work_name")->where(['status'=>1,'hospital_id'=>$hospital_id])->get()->toArray();
        $data = DB::table('c_doctor_works as m')
            ->select('m.work_name', 'm.id', 'm.clinic_id','d.real_name', 'c.classify_name')
//            ->leftJoin('c_orders as o', 'm.id', '=', 'o.work_id')
            ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')
            ->leftJoin('c_doctors as d', 'm.id', '=', 'd.work_id')
            ->whereIn("m.id", $work_ids)
            ->where("d.is_admin",'=',1)
            ->where($w)
            ->groupBy('m.id')
            ->orderBy('m.id', 'desc')
            ->paginate(10);
        //已随访的工作室数
        foreach ($data->items() as &$v) {
            $v->order = '否';
            $order = (new Order())->where("work_id", $v->id)->whereIn("order_type",[3,4])
                ->where("pay_status",'=',1)
                ->where("order_status",'<',2)
                ->first();
            if($order){
                $v->order = '是';
            }
        }
        return view('admin.workaddconsultlist', compact('data','w_id','work_list'));
    }


    /**
     * @param Request $request
     * @return
     * 病种统计
     */
    public function getDiseaseTypeList(Request $request)
    {
        $userid = auth()->user()->id ?? 0;
        $types = auth()->user()->types;
        $hospital_id = auth()->user()->hospital_id;
        $page= $request->query("page")?$request->query("page"):1;
        $start = ($page-1)*10;
        //判断用户是否是医院账号
        $role_list = AdminRoleUser::where(['user_id'=>$userid])->pluck("role_id")->toArray();
        if (!$userid || $types !=4 || $hospital_id ==0 || !in_array(11,$role_list)) {
            return redirect("admin/auth/logout");
        }
        $work_ids = (new DoctorWorks())->where(['status'=>1,'hospital_id'=>$hospital_id])->pluck("id")->toArray();
//        $work_list = (new DoctorWorks())->select("id","work_name")->where(['status'=>1,'hospital_id'=>$hospital_id])->get()->toArray();
        $list = DB::table('c_address_book_labels as c')
            ->select('c.label_name', "c.lab_type")
            ->where("c.lab_type", '=', 1)
            ->whereIn("c.work_id", $work_ids)
            ->groupBy('c.label_name')
            ->get();
        $lit = [];
        foreach ($list as $k=>$v) {
            $vall = DB::table('c_address_book_relate_labels as m')
                ->leftJoin('c_address_books as o', 'm.address_book_id', '=', 'o.id')
                ->leftJoin('c_address_book_labels as c', 'm.address_book_label_id', '=', 'c.id')
                ->where("c.lab_type", '=', 1)
                ->where('label_name', '=', $v->label_name)
                ->groupBy('o.user_id')
                ->whereIn("m.work_id", $work_ids)
                ->get()
                ->count();
            if($vall ==0){
                continue;
            }
            $lit[$k]['name'] = $v->label_name;
            $lit[$k]['value'] = $vall;
        }
        $name = [];
        $value = [];
        if(!empty($lit)){
            $count = count($lit);
            $order_count = array_column($lit, 'value');
            array_multisort($order_count, SORT_DESC, $lit);
            $lit =  array_slice($lit,$start,10);
            foreach ($lit as $vv){
                $name[] = $vv['name'];
                $value[] = $vv['value'];
            }
        }
        $val['name'] = $name;
        $val['value'] = $value;
        $result['list'] = $lit;
        $result['val'] = $val;
        $result['total'] = $count;
        $result['page'] = $page;
        $result['page_total'] = ceil($count/10);
        return view('admin.diseasetypelist', compact('result'));
    }




    /**
     * @param $w_ids
     * @return array
     * 工作室创作排名
     */
    public function getWorkCreateNumberList(Request $request)
    {
        $userid = auth()->user()->id ?? 0;
        $types = auth()->user()->types;
        $hospital_id = auth()->user()->hospital_id;
        $page= $request->query("page")?$request->query("page"):1;
        $w_id = $request->query("w_id")??"";
        $w = [];
        if(!empty($w_id)){
            $w[] = ['m.id','=',$w_id];
        }
        $start = ($page-1)*10;
        //判断用户是否是医院账号
        $role_list = AdminRoleUser::where(['user_id'=>$userid])->pluck("role_id")->toArray();
        if (!$userid || $types !=4 || $hospital_id ==0 || !in_array(11,$role_list)) {
            return redirect("admin/auth/logout");
        }
        $work_list = (new DoctorWorks())->select("id","work_name")->where(['status'=>1,'hospital_id'=>$hospital_id])->get()->toArray();
        $work_ids = (new DoctorWorks())->where(['status'=>1,'hospital_id'=>$hospital_id])->pluck("id")->toArray();
        $works = DB::table('c_doctor_works as m')
            ->select('m.work_name', 'm.id', 'm.clinic_id', 'c.classify_name')
            ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')
            ->whereIn("m.id", $work_ids)
            ->where($w)
            ->get()->toArray();
//        $works = DoctorWorks:: ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')whereIn("id", $w_ids)->select("work_name", "id")->get()->toArray();
        foreach ($works as &$v) {
            $art_count = Article::where("work_id", '=', $v->id)->count();
            $course_count = Course::where("work_id", '=', $v->id)->where("audit_status",'=',2)->count();
            $v->order_count = $art_count + $course_count;
        }
        $count = count($works);
        $order_count = array_column($works, 'order_count');
        array_multisort($order_count, SORT_DESC, $works);
        $lit =  array_slice($works,$start,10);
        $result['list'] = $lit;
        $result['total'] = $count;
        $result['page'] = $page;
        $result['page_total'] = ceil($count/10);
        return view('admin.workcreatenumberlist', compact('result','work_list','w_id'));
    }




}
